package org.qloudgen.txn.dilithium.cluster.security;

import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.Session;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.authorization.IAuthorizationStrategy;
import org.apache.wicket.markup.html.pages.AccessDeniedPage;
import org.apache.wicket.request.component.IRequestableComponent;
import org.qloudgen.txn.dilithium.cluster.pages.common.InternalErrorPage;

public class DilithiumAuthorizationStrategy implements IAuthorizationStrategy {

	private boolean flag = false;
	public <T extends IRequestableComponent> boolean isInstantiationAuthorized(
			Class<T> componentClass) {
		
		 if (!Page.class.isAssignableFrom(componentClass)) {         
			 return true;      
		 }        
		 
		 if (LoginPage.class.isAssignableFrom(componentClass)) {         
			 return true;      
		 }     
		 
		 if (CreateUserPage.class.isAssignableFrom(componentClass)) {         
			 return true;      
		 }      
		 
		 if (AccessDeniedPage.class.isAssignableFrom(componentClass)) {   
			 flag = false;
			 return true;      
		 } 
		 
		 if (checkAuthorization(componentClass)) {         
			 if (!flag) throw new RestartResponseAtInterceptPageException(LoginPage.class);      
		 }      
		 	 if (flag) throw new RestartResponseAtInterceptPageException(AccessDeniedPage.class);  
		 return true;
	}
	
	private <T> boolean checkAuthorization(Class<T> componentClass)  {
		
		//authorization of pages , for example, non-super user can not view swe can set more complicated authorization model here
		if (((DilithiumSession)Session.get()).getUserNo() != null) {
			try {
//				if (!((DilithiumSession)Session.get()).getUserID().equals("super") && (Class.forName("org.qloudgen.txn.dilithium.cluster.pages.AddNodePages")).isAssignableFrom(componentClass)) {
//					flag = true;
//				}
				flag = false;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		//check if user have already logged in
		return !((DilithiumSession)Session.get()).isUserLoggedIn();

	}

	public boolean isActionAuthorized(Component component, Action action)
	{
		//authorization of elements, auth_type : no-read,read-only,read-write
		/*if (action == Component.ENABLE && component.getId().equals("clusterID")) return false;
		if (action == Component.RENDER && component.getId().equals("clusterID")) return false;*/
		return true;
	}
	
}

